import { Http } from '../utils/http/Http';
import { HttpStorage } from '../utils/http/HttpStorage';
import { LoginRequest, UserInfo, UploadAdRecordRequest, UserAdInfo, AppDetail } from './type/user';
import type {
  RefreshTokenRequest,
  RefreshTokenResponse
} from './type/user';
import { SignManager } from '../utils/SignManager';

export const UserApi = {
  /** 
   * 用户登录
   * @param params 登录请求参数
   * @returns 用户信息
   */
  async login(params: LoginRequest): Promise<UserInfo> {
    const res = await Http.post<UserInfo>('/api/Third/login', params);
    console.log("login userInfo", JSON.stringify(res));
    
    // 保存token到HttpStorage
    if (res && res.userInfo && res.userInfo.token) {
      HttpStorage.set('token', res.userInfo.token);
      console.log("login token", res.userInfo.token);
    }
    
    return res;
  },

  // 获取应用详情
  async getAppDetail(app_id: string): Promise<AppDetail> {
    return await Http.get<AppDetail>('/api/app/getAppDetail', {"app_id": app_id}, {
      skipAuth: true
    });
  },

  /** 
   * 刷新 Token 
   * @param params 刷新Token请求参数
   * @returns Token刷新响应
   */
  async refreshToken(params: RefreshTokenRequest): Promise<RefreshTokenResponse> {
    return await Http.post<RefreshTokenResponse>('/api/user/refreshToken', params, {
      skipAuth: true 
    });
  },

  /** 
   * 上传广告记录 
   * @param params 广告记录请求参数
   * @returns 结果信息
   */
  async uploadAdRecord(params: UploadAdRecordRequest): Promise<string> {
    return await Http.post<string>('/api/ad/add', params);
  },

  /** 
   * 获取用户广告信息 
   * @returns 用户广告信息
   */
  async getUserAdInfo(appid: string): Promise<UserAdInfo> {
    return await Http.post<UserAdInfo>('/api/user/getUserAdInfo', {appid});
  },

  /** 
   * 退出登录 
   */
  async logout(): Promise<void> {
    return await Http.post<void>('/api/user/logout', {});
  },

  /**
   * 游客登录
   * @param deviceId 设备ID
   * @returns 登录结果
   */
  async guestLogin(deviceId: string): Promise<UserInfo> {
    const signature = SignManager.generateSignature(deviceId);
    
    const payload = {
      device_id: deviceId,
      sign: signature
    };

    console.log("guestLogin payload", payload);
    const res = await Http.post<UserInfo>('/api/Third/guestLogin', payload, {
      skipAuth: true
    });

    // 保存token到HttpStorage
    if (res && res.userInfo && res.userInfo.token) {
      HttpStorage.set('token', res.userInfo.token);
      console.log("login token", res.userInfo.token);
    }

    return res;
        
  }
};
